package main

import (
	"fmt"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

var db *sqlx.DB

type userInfo struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

var dsn string = "root:root333@tcp(127.0.0.1:3306)/go_sql_test"

func initDB() (err error) {
	db, err = sqlx.Connect("mysql", dsn)
	if err != nil {
		fmt.Printf("connect server failed, err:%v\n", err)
		return
	}
	db.SetMaxOpenConns(200)
	db.SetMaxIdleConns(10)
	fmt.Println("数据库连接成功")
	return nil
}
func main() {
	initDB()

	// 查询单条
	sqlStr1 := "select name,age from user where id=1"
	var u userInfo
	db.Get(&u, sqlStr1) // 此处使用了指针+反射
	fmt.Printf("u: %v\n", u)
	//查询多条
	sqlStr2 := "SELECT age,name from user where id >= ?"
	var userList []userInfo
	err := db.Select(&userList, sqlStr2, 1)
	if err != nil {
		fmt.Println("查询失败:", err)
		return
	}
	fmt.Println("userList:", userList)

}
